package org.example.dev.controller;


import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import org.example.dev.common.Result;
import org.example.dev.pojo.User;
import org.example.dev.service.IUserService;
import org.example.dev.service.Impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;

import static cn.dev33.satoken.stp.StpUtil.getLoginId;
import static org.example.dev.service.hassPassword.hashPassword;


/**
 * @author 梁祖杰
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    private final IUserService iUserService;
    private final UserServiceImpl userServiceImpl;

    public UserController(IUserService iUserService, UserServiceImpl userServiceImpl) {
        this.iUserService = iUserService;
        this.userServiceImpl = userServiceImpl;
    }

    @PostMapping("/register")//注册
    public Result register(@RequestBody User user) {
        User existingUserByEmail = iUserService.findUserByEmail(user.getEmail());//邮箱唯一检测
        User existingUserByPhone = iUserService.findUserByPhone(user.getPhone());//手机号唯一检测
        // 返回错误信息，邮箱或手机号已存在
        //409 Conflict：请求冲突，通常用于资源已经存在的情况，例如手机号或邮箱重复
        if (existingUserByEmail != null)
            return Result.error("该邮箱已注册");
        if (existingUserByPhone != null)
            return Result.error("该手机号已注册");
        //创建新用户并保存到数据库
        iUserService.register(user.getUsername(), user.getPassword(), user.getPhone(), user.getEmail(), user.getAvatar());
        return Result.success("用户注册成功");
    }


    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/login")//登录
    public SaResult login(@RequestBody User user)  {
        User existingUserByEmail = iUserService.findUserByEmail(user.getEmail());
        if (existingUserByEmail == null)
            return SaResult.error("该邮箱不存在");
        User loggedUser = iUserService.login(user.getPassword(), user.getEmail());
        if (loggedUser != null) {
            StpUtil.login(loggedUser.getUserId());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return SaResult.data(tokenInfo);
        }
        return SaResult.error("密码错误");

    }

    /**
     * 查询登录状态
     * @return
     */
    @RequestMapping("/isLogin")
    public SaResult isLogin() {
        return SaResult.ok("登陆状态："+ StpUtil.isLogin());
    }

    /**
     * 查询登录用户信息
     * @return
     */
    @RequestMapping("/getUser")
    public User getUser() {
        return iUserService.getCurrentUser();
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
//    /**
//     * 发送短信
//     * @param phone
//     * @return
//     */
//    @PostMapping("/sendPhoneVerificationCode")//发短信
//    public ResponseEntity<String> sendPhoneVerificationCode(@RequestParam String phone) {
//        User existingUserByPhone = iUserService.findUserByPhone(phone);//用于判断手机号是否存在
//        if(existingUserByPhone==null){//返回错误信息，404 Not Found:请求的手机号码不存在
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Phone number does not exist");
//        }
//        else{
//            try {
//                iUserService.sendPhoneVerificationCode(phone);
//                return ResponseEntity.ok("Verification code sent successfully");
//            } catch (Exception e) {//发送短信失败
//                //500 Internal Server Error:服务器内部错误
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to send verification code: " + e.getMessage());
//            }
//        }
//    }

    @PostMapping("/sendLoginEmailVerificationCode")//发邮件
    public Result<?> sendLoginEmailVerificationCode(@RequestParam String email) {
        User user = new User();
        user = iUserService.findUserByEmail( email);
        if(user == null ){
            return Result.error("邮箱不存在!");
        }
        try {
            String verificationCode = iUserService.sendEmailVerificationCode(email);
            return Result.success(verificationCode);
        } catch (Exception e) {//发送邮件失败
            return Result.error("发送邮件失败: " + e.getMessage());
        }
    }

    @PostMapping("/sendEmailVerificationCode")//发邮件
    public Result<?> sendEmailVerificationCode(@RequestParam String email) {
        User user = new User();
        user = iUserService.findUserByEmail( email);
        if(user != null ){
            return Result.error("该邮箱已被注册!");
        }
        try {
            String verificationCode = iUserService.sendEmailVerificationCode(email);
            return Result.success(verificationCode);
        } catch (Exception e) {//发送邮件失败
            return Result.error("发送邮件失败: " + e.getMessage());
        }
    }


    @PutMapping("/resetPassword")//改密码
    public Result<?> resetPassword(@RequestParam String email, @RequestParam String password, @RequestParam String newPassword ) {
        User resetPasswordUser = iUserService.resetPassword(email,password,newPassword);
        if (resetPasswordUser != null) {
            return Result.success("修改密码成功");
        } else {//400 Bad Request:请求参数错误,改密码失败
            return Result.error("修改密码失败");
        }
    }

    @PostMapping("/forgetPassword")
    public Result<?> forgetPassword(@RequestBody  User user) {
        User resetPasswordUser = iUserService.forgetPassword(user.getEmail(),user.getPassword());
        return Result.success("密码设置成功");
    }

    /**
     * 修过用户头像
     */
    @PostMapping("/updateAvatar")
    public Result<?> updateAvatar(@RequestBody User user) {
        user.setUserId(iUserService.getCurrentUser().getUserId());
        if(user.getUserId() == null){
            return Result.error("未知用户");
        }
        if(StrUtil.isBlank(user.getAvatar())){
            return Result.error("未知图片");
        }
        iUserService.updateAvatar(user);
        return Result.success("头像更新成功");
    }

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PostMapping("/update")
    public Result<?> update(@RequestBody User user) {
        user.setUserId(iUserService.getCurrentUser().getUserId());
        if(user.getUserId() == null){
            return Result.error("未知用户");
        }
        return Result.success(iUserService.update(user));
    }
}
